import { NextResponse } from 'next/server';
import { query } from '@/lib/database';
import { hashPassword, generateToken } from '@/lib/auth';

export async function POST(request: Request) {
  try {
    const { username, email, password } = await request.json();

    // 检查用户是否存在
    const existingUsers = await query(
      'SELECT id FROM users WHERE username = ? OR email = ?',
      [username, email]
    ) as any[];

    if (existingUsers.length > 0) {
      return NextResponse.json(
        { error: '用户名或邮箱已存在' },
        { status: 400 }
      );
    }

    // 加密密码并创建用户
    const hashedPassword = await hashPassword(password);
    
    const result = await query(
      'INSERT INTO users (username, email, password) VALUES (?, ?, ?)',
      [username, email, hashedPassword]
    ) as any;

    // 生成token
    const token = generateToken({
      userId: result.insertId,
      username
    });

    return NextResponse.json({
      message: '注册成功',
      token,
      user: { id: result.insertId, username, email }
    });
  } catch (error) {
    console.error('注册错误:', error);
    return NextResponse.json(
      { error: '服务器错误' },
      { status: 500 }
    );
  }
}